home *** CD-ROM | disk | FTP | other *** search
- Path: news.mira.net.au!news
- From: davidw@werple.net.au (David White)
- Newsgroups: comp.lang.c++
- Subject: Re: Question about visibility of local variables
- Date: 5 Mar 1996 20:30:02 +1100
- Organization: Werple Internet, Melbourne
- Message-ID: <4hh1iq$pvr@werple.net.au>
- References: <4hfkpc$9em@guardian.forbin.com>
- NNTP-Posting-Host: werple.mira.net.au
-
- genesis@forbin.com (Dances with Demons) writes:
-
- >I am in the process of learning C++ which surprised me in being
- >as awesome as everyone kept telling me. It is literally better
- >than anything I ever expected. I ran into one dark area for me
- >in the area of automatic variables.
- > It said in the book I'm studying, "Object-Oriented Programming
- >in C++, by Robert Lafore", that when a function is executed, the
- >and the variable is defined, it will continue to exist until the
- >function is exited. When this happens, the memory that the variable
- >is freed up and is used by other variables/function calls, etc.
-
- >The question is: When you define a variable in main(), and call another
- >function, or even when defining a local variable in a function that calls
- >another function, why are the local variables not destroyed.
- > I had a thought that maybe since main() called the function, it still had
- >control, (at least as far as variable usage went) and therefore didn't
- >free up the memory until the function is actually completed, (End
- >of the program), but I wasn't sure. Could someone please verify that this is
- >indeed the case, or refute it and give me the real reason.
-
- Automatic variables are created on the program's stack. A stack is a
- last-on, first-off form of data storage, like a stack of trays at some
- take-away food restaurants. When a function is entered, local variables
- are "pushed" onto the stack and "popped" off when the function exits. If a
- function calls another function, any local variables in the called
- function are pushed onto the stack also, on top of the ones the calling
- function created for itself. Therefore, the stack keeps growing higher as
- more functions within functions are entered. As each function returns, its
- own variables are popped off, leaving the stack in the state it was before
- the function was called, i.e., with the calling function's variables on
- top once again. So nothing is destroyed when another function is called.
- This means that local variables in 'main' survive for the entire duration
- of the program (barring disaster, or a call to exit()). Parameters passed
- to functions are also stored on the stack.
-
- David White
- davidw@werple.mira.net.au
-